<?php namespace module\button\controller;

use houdunwang\request\Request;
use houdunwang\wechat\WeChat;
use module\HdController;
use system\model\Button as ButtonModel;
class Button extends HdController
{

	public function index ()
	{
		$field = ButtonModel::get();
		return $this->template('',compact('field'));
	}

	//添加回复
	public function post ()
	{
		$id = Request::get('id');
		$model = ButtonModel::find($id) ? : new ButtonModel();
		if(IS_POST)
		{
			//p($_POST);die;
			$post = Request::post();
			if($id)
			{
				$post['state'] = 1;
			}
			else
			{
				$post['state'] = 0;
			}
			$model->save($post);
			return $this->setRedirect(url('button.index'))->success('操作成功');
		}
		//这里需要特殊考虑添加，在模板页面中button对应的就不存在，js报错
		if(!$id){
			$model = ['title'=>'','content'=>'[]'];
		}
		return $this->template('',compact('model'));
	}
	/**
	 * 删除
	 *
	 */
	public function del()
	{
		$id = Request::get('id');
		//p($id);die;
		//删除回复内容
		$model = ButtonModel::find($id);
		$model->destory();
		//成功提示
		return $this->setRedirect(url('button.index'))->success('操作成功');
	}
	/*
	 * 推送微信菜单
	 */
	public function send()
	{
		//接受get参数
		$id = Request::get('id');
		//根据id在数据库中对应的数据
		$data = ButtonModel::find($id)->content;
		$button['button'] = json_decode($data,true);
		//菜单数据推送成功
		//是否使用的是测试账号,appid和appsecret是不是测试账号参数
		$res = WeChat::instance('button')->create($button);

		if($res['errcode']==0){
			//代表推送成功
			//进行状态修改
			Db::table('button')->where("id",$id)->update(['state'=>1]);
			//把其他的菜单状态修改为0
			Db::table('button')->where("id",'<>',$id)->update(['state'=>0]);
			return $this->setRedirect(url('button.index'))->success('菜单推送成功');
		}else{
			return $this->error('错误码：' . $res['errcode'] . '；错误消息'.$res['errmsg']);
		}
	}
}